<?php
namespace app\task\controller;
use app\task\logic\CpFormBranchMonthLogic;

/**
 * 社区巡店分部报表（月）api控制器
 * Created by PhpStorm.
 * User: tyll
 * Date: 2019/09/25
 * Time: 16:11
 */
class CpFormBranchMonth extends Base {

    public function __construct(){
        parent::__construct();
        $this->cfbm_logic = new CpFormBranchMonthLogic();
    }

    /**
     * 处理报表
     * @return \think\response\Json
     */
    public function deal_form(){
        $now_time = date('Y-m-d H:i:s');

        $branchids = model('branch')->get_column([],'id');
        foreach($branchids as $k => $v){
            //获取需要计算的时间
            $r = $this->cfbm_logic->get_count_time($v,$now_time);
            if(!$r['code']){
                continue;
            }
            $start_time = $r['data']['start_time'];
            $end_time = $r['data']['end_time'];
            $timeid = $r['data']['timeid'];

            //查找该月是否已计算数据
            $maps = [];
            $maps[] = ['branchid','=',$v];
            $maps[] = ['timeid','=',$timeid];
            $cfbm_detail = model('cp_form_branch_month')->get_detail($maps,'id');

            //计算分部社区已巡店次数
            $cp_branch_num = $this->cfbm_logic->count_cp_branch_num($v,$start_time,$end_time);

            //计算分部社区未巡店次数
            $cp_branch_no_num = $this->cfbm_logic->count_cp_branch_no_num($v,$start_time,$end_time);

            $cfbm_data = [];
            $cfbm_data['branchid'] = $v;
            $cfbm_data['cp_branch_num'] = $cp_branch_num;
            $cfbm_data['cp_branch_no_num'] = $cp_branch_no_num;
            $cfbm_data['timeid'] = $timeid;

            //更新数据
            if(empty($cfbm_detail)){
                $r = model('cp_form_branch_month')->insert($cfbm_data);
            }else{
                $maps = [];
                $maps[] = ['id','=',$cfbm_detail['id']];
                $r = model('cp_form_branch_month')->where($maps)->update($cfbm_data);
            }
        }
        return json($this->cfbm_logic->get_response(1,'处理分部报表，日期：' . $now_time));
    }
}